// packageA/pages/equipmentMaintainAdd/equipmentMaintainAdd.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //是否是修改
    isEdit:false,
    //修改信息回显
    editInfo:{},
    //库存信息
    repertoryInfo:null,
    //提交按钮禁用
    disabled:false,
    //配件列表
    partList:[],
    //当前配件
    currentPart:null,
    //当前配件
    currentIndex:0,
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //搜索词
    valueSearch:'',
    //开始时间选择框
    showStartTime:false,
    //结束时间选择框
    showEndTime:false,
    //当前时间
    currentStart: new Date().getTime(),
    currentEnd: new Date().getTime(),
    //最小时间
    minDate2: null,  
    //时间格式
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } else if (type === 'hour') {
        return `${value}时`
      } else if (type === 'minute') {
        return `${value}分`
      } else if (type === 'second') {
        return `${value}秒`
      }
      return value
    },
    //是否只读
    readOnly:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.getUserProfile({
      desc: '为您提供更好的服务',
      success: (res) => {}
    })
    
    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('添加保养传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })
      
      //是否只读
      if(paramObj.readOnly){ 
        this.setData({
          readOnly: true
        })
      }

      //获取库存信息
      if(paramObj.repertoryId){
        //获取库存信息
        this.getRepertory();
      }

      if(paramObj.id){
        this.setData({
          id: paramObj.id
        })
        //获取修改的数据
        this.getInfo();
      }
    }
  },

  //提交表单
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })
 
    let obj=e.detail.value;
    let editInfo=this.data.editInfo;
    let rInfo=this.data.repertoryInfo;
    let partList=this.data.partList;

    //开始和结束时间必填
    if(!editInfo.startDate){
      Toast.fail('请选择开始时间');
      return;
    }
    if(!editInfo.endDate){
      Toast.fail('请选择结束时间');
      return;
    }

    //时间大小
    if(editInfo.startDate>editInfo.endDate){
      Toast.fail('结束时间不能早于开始时间');
      return;
    }

    //保养人员必填
    if(!editInfo.maintainer){
      Toast.fail('请选择保养人员');
      return;
    }

    //配件必填
    if(partList.length){
      let len=partList.length-1;
      if(partList[len].depot && partList[len].name){
        //处理配件列表数据
        partList.forEach((item,index) => {
          item.index=index;
          item.partsSumAmount=item.partsPrice * item.partsNum;
        });
      }else{
        Toast.fail('请添加完整配件信息');
        return;
      }
    }

    let param={
      appId: [app.globalData.myAppId],
      state: 3,
      maintain:[{
        id: this.data.id,
        repertoryId: this.data.paramObj.repertoryId,
        createDate: util.timeFormat(new Date()),
        startDate: editInfo.startDate,
        endDate: editInfo.endDate,
        equipmentNo: rInfo.equipmentNo ? rInfo.equipmentNo : '',
        maintainer: editInfo.maintainer,
        parts: partList,
        index: 0,
        remarks: obj.remarks.trim()
      }]
    }

    //合并对象
    Object.assign(param,rInfo); 

    //console.log(param);

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });

    CommonService.checkItem(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //获取库存信息
  getRepertory(){
    let param = {
      isAuth: false,
      className: 'repertory',
      data: {
        id: this.data.paramObj.repertoryId,
        type: 1,
        selectFields: ["id","equipmentNo","imei","type", "num","category", "createDate", "name", "spec","unit","depot","relationOrderNo","leaseRecord","ioStorageDetail","performance","remarks","checkRecord","testRecord","checkRemarks","orderObj","service","keepAccounts","dataAuthority","accountingPrice"]
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];
        console.log('库存信息');
        console.log(result);

        this.setData({
          repertoryInfo: result
        })
      }
    }).catch((error) => {
    })
  },

  //获取修改的数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'maintain',
      data: {
        id:this.data.id,
        selectFields: ['id','parts','startDate','endDate','equipmentNo','maintainer','repertoryId','createDate','remarks']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];
        console.log('保养信息回显');
        console.log(result);

        //处理配件显示名称
        if(result.parts && result.parts.length){
          result.parts.forEach(item => {
            item.name=item.partsObj.name;
          });
        }

        this.setData({
          editInfo: result
        })

        if(result.parts && result.parts.length){
          this.setData({
            partList: result.parts
          })
        }
      }
    }).catch((error) => {
    })
  },

  //添加配件
  onAddPart(){
    let list=this.data.partList;
    
    if(list.length){
      //未填写不能加新的
      if(list[list.length-1].name){
      }else{
        Toast.fail('当前配件信息未完成');
        return;
      }
    }

    list.push({
      id: null,
      depot: null,     
      partsNum: 1,      
      partsObj: null,
      partsPrice: null,
      purchasePrice: null,
      unit: null,
      name: ''
    });

    this.setData({ 
      partList: list,
      disabled: false 
    })
  },

  //显示选择框
  onShowSelect(e){
    if(!this.data.readOnly){
      this.setData({
        selectList: []
      })
      
      let dataset=e.target.dataset;
      let field=dataset.field;   
      
      this.setData({
        showSelect: true,
        selectField: field
      }) 

      //配件库
      if(field=='depot'){
        this.setData({
          selectTitle: '配件库',
          showSelectSearch:true,
          currentIndex:dataset.index,
          currentPart:dataset.current
        })
        this.getDepotList();
      }

      //配件名称
      if(field=='partName'){      
        if(dataset.current.depot){
          this.setData({
            selectTitle: '配件',
            showSelectSearch:false,
            currentIndex:dataset.index,
            currentPart:dataset.current
          })
          this.getPartList();
        }else{
          Toast.fail('请先选择配件库');
        }  
      }

      //保养人员
      if(field=='user'){
        this.setData({
          selectTitle: '保养人员',
          showSelectSearch: true
        })
        this.getUserList();
      }
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    this.setData({
      valueSearch: '',
      disabled: false
    })

    //配件库
    if(selectField=='depot'){
      let obj=e.detail.value.obj;
      let currentIndex=this.data.currentIndex; 
      let partList=this.data.partList;

      //处理配件列表
      partList.forEach((item,index) => {
        if(index==currentIndex){
          item.depot=obj;
        }
      });

      this.setData({
        partList:partList,
        disabled: false
      })
    }

    //配件名称
    if(selectField=='partName'){
      let obj=e.detail.value.obj;

      //配件数量为0不能添加
      if(obj.num==0){
        Toast.fail('当前配件库存为0，不能添加');
        return;
      }

      let currentIndex=this.data.currentIndex;
      let partList=this.data.partList;

      //不能重复
      if(partList.length>1){
        let flag=partList.some(item=>{
          return item.id==obj.id;
        });
        if(flag){      
          Toast.fail('当前配件已添加，请修改数量');
          return;
        }
      }  
    
      partList.forEach((item,index) => {
        if(index==currentIndex){ 
          this.getPartInfo(obj.code).then(value => {
            if(value){
              item.id = obj.id; 
              item.partsObj = obj;
              item.partsPrice = value.factory.salePrice;
              item.purchasePrice = value.factory.purchasePrice;
              item.unit = obj.unitName;
              item.name = obj.name;
              item.stockNum=obj.num;
            }else{
              Toast.fail('配件信息有误，请联系管理员');
              return;
            }
          });  
        }
      });

      //延迟选择配件
      Toast.loading({
        duration: 1000,
        forbidClick: true,
        message: '查询配件请稍等'
      });

      setTimeout(() => {
        this.setData({
          partList:partList,
          disabled: false
        })
      }, 1000);

    }

    //保养人员
    if(selectField=='user'){
      obj='editInfo.maintainer';
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }
    this.onCloseSelect();
  },  

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;    
    
    this.setData({
      valueSearch: e.detail,
      selectList: []
    })

    //配件库
    if(selectField=='depot'){
      this.getDepotList();
    }

    //保养人员
    if(selectField=='user'){
      this.getUserList();
    }
  },

  //查询配件库
  getDepotList(){
    let param = {
      isAuth: true,
      className: 'partsDepots',
      data: {
        searchAll: true,
        selectFields: ['id','name','keeper']
      }
    }
   
    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });
        
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //查询配件
  getPartList(){
    let param = {
      isAuth: true,
      className: 'repertory',
      data: {
        'depot.id': this.data.currentPart.depot.id,
        type: 2,
        searchAll: true,
        selectFields: ['id', 'name', 'factory', 'code','num', 'spec','unitName']
      }
    }  

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;

        console.log('配件列表');
        console.log(result);

        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });
        
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //获取配件数量
  onChangeNum(e) {
    let list=this.data.partList;
    let dataset=e.currentTarget.dataset;
    
    list.forEach((item,index) => {
      if(index==dataset.index){
        item.partsNum=e.detail;
      }
    });

    this.setData({ 
      partList: list 
    })
  },

  //删除配件
  ondeletePart(e){
    Dialog.confirm({
      title: '确认删除此配件吗',
      confirmButtonText:'确认',
      cancelButtonText:'不删除了'
    }).then(() => {
      let list=this.data.partList;
      let dataset=e.currentTarget.dataset;
      let arr=[];
      
      list.forEach((item,index) => {
        if(index!=dataset.index){
          arr.push(item);
        }
      });
  
      this.setData({ 
        partList: arr 
      }) 
    }).catch(() => {
    });  
  },

  //查询配件信息
  getPartInfo(code){
    let param = {
      isAuth: false,
      className: 'partsFactory',
      data: {
        code: code,
        selectFields: ['id','name','params','specs','factory','code']
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param).then(res=>{
        if (res.data.data && res.data.data.result && res.data.data.result.length) {
          resolve(res.data.data.result[0]);
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },

  //显示开始时间
  onShowStartTime(){
    if(!this.data.readOnly){
      this.setData({
        showStartTime: true
      })
    }  
  },

  //隐藏开始时间
  onCloseStartTime(){
    this.setData({
			showStartTime: false
    })
  },

  //确认开始时间
  onConfirmStartTime(e) {
    let start='editInfo.startDate';
    this.setData({
      currentStart: e.detail,
      minDate2:e.detail,
      [start]:util.timeFormat(e.detail),
      disabled:false
    })
    this.onCloseStartTime();
  },

  //显示结束时间
  onShowEndTime(){
    if(!this.data.readOnly){
      this.setData({
        showEndTime: true
      })
    }  
  },

  //隐藏结束时间
  onCloseEndTime(){
    this.setData({
			showEndTime: false
    })
  },

  //确认结束时间
  onConfirmEndTime(e) {
    let end='editInfo.endDate';
    this.setData({
      currentEnd: e.detail,
      [end]:util.timeFormat(e.detail),
      disabled:false
    })
    this.onCloseEndTime();
  },

  //查询保养人员
  getUserList(){
    let param = {
      isAuth: true,
      className: 'user',
      data: {
        depart: 1,
        searchAll: true,
        selectFields: ['id','userName']
      }
    }
   
    if(this.data.valueSearch){
      param.data.userName='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.userName,
            id:item.id,
            obj:{
              id:item.id,
              name:item.userName
            }
          });
        });
        
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    let prevPage2 = pages[pages.length - 3];

    prevPage.refreshListAndPage();
    prevPage2.refreshListAndPage();
    wx.navigateBack();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  }
})